package com.translation.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.translation.utils.Encrypt;

public class SessInterceptor extends HandlerInterceptorAdapter {

	private static final String LAST_PATH = "com.translation.path";
	private static final String[] allowURL = {"/index","/","/unlog","error"};
	private static final String[] allowMethod = {"cancel","log"};
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String requestURL = request.getRequestURI();
		String method = request.getParameter("method");
		if(requestURL.equals("/user"))
		{
			for(String met : allowMethod)
			{
				if(met.equals(method))
				{
					return true;
				}
			}
		}
		for (String url : allowURL) {
			if (url.equals(requestURL))
				return true;
		}
		if(request.getSession().getAttribute("user")!=null){
			return true;
		}else {
			StringBuffer url = new StringBuffer(request.getRequestURI());
			if(request.getParameter("method")!=null)
				url.append("?method="+request.getParameter("method"));
			request.getSession().setAttribute(LAST_PATH, Encrypt.encode(url.toString()));
			response.sendRedirect("unlog");			
			return false;
		}
		
	}
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

}
